<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/26
 * Time: 11:36
 */

namespace app\api\controller;


use app\api\service\Goods;
use app\common\Code;
use app\common\Crypt;
use app\common\model\Community;
use app\common\model\GoodsCategory;
use app\common\model\OrderTrade;
use app\common\model\Trade;
use app\common\PaySuccess;
use app\common\Session;

class V3
{
    /**
     * <span style="color:#ccc;">对签名字符串转义 [不是app接口]</span>
     * @param $para
     * @return string
     */
    private function createLinkstring($para)
    {
        $arg = "";
        while (list ($key, $val) = each($para)) {
            $arg .= $key . '="' . $val . '"&';
        }
        //去掉最后一个&字符
        $arg = substr($arg, 0, count($arg) - 2);
        //如果存在转义字符，那么去掉转义
        if (get_magic_quotes_gpc()) {
            $arg = stripslashes($arg);
        }
        return $arg;
    }

    /**
     * <span style="color:#ccc;">签名生成订单信息 [不是app接口]</span>
     * @param $data
     * @return string
     */
    private function rsaSign($data)
    {
        $priKey = Config("alipay_rsa_private");
        $res = openssl_pkey_get_private($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        return $sign;
    }


    /**
     * 支付宝支付
     * 参数  code 交易码
     * @param $code
     * @return \think\response\Jsonp
     */
    function do_alipay_old($code)
    {
        $payment = new \app\common\model\Trade();
        /** @var \app\common\model\Trade $payment_item */
        $payment_item = $payment->get(["code" => $code, "is_pay" => 0]);
        if (empty($payment_item)) {
            response_json(Code::FAIL);
        }
        $fee = $payment_item->value;
        $fee = abs($fee);
        //异步通知地址  需http://格式的完整路径，不允许加?id=123这类自定义参数
        $notify_url = sprintf("%s/%s/code/%s",
            config('site_url'),
            "index/pay/alipay_notify_back",
            $code); //服务器异步通知页面路径
        $parameter = array(
            'service' => 'mobile.securitypay.pay',   // 必填，接口名称，固定值
            'partner' => config("alipay_partner"),                   // 必填，合作商户号
            '_input_charset' => 'UTF-8',                    // 必填，参数编码字符集
            'out_trade_no' => $code,              // 必填，商户网站唯一订单号
            'subject' => "交易码$code",                   // 必填，商品名称
            'payment_type' => '1',                        // 必填，支付类型
            'seller_id' => config('alipay_partner'),                 // 必填，卖家支付宝账号
            'total_fee' => $fee,                     // 必填，总金额，取值范围为[0.01,100000000.00]
            'body' => " ",                      // 必填，商品详情
            'it_b_pay' => '1d',                       // 可选，未付款交易的超时时间
            'notify_url' => $notify_url,                // 可选，服务器异步通知页面路径
            'show_url' => config('site_url')                  // 可选，商品展示网站
        );
        //生成需要签名的订单
        $orderInfo = $this->createLinkstring($parameter);
        //签名
        $sign = $this->rsaSign($orderInfo);
        //生成订单
        $order = $orderInfo . '&sign="' . $sign . '"&sign_type="RSA"';
        response_json(Code::NONE, $order);
    }


    /**
     * 支付宝支付
     * 参数  code 交易码
     * @param $code
     * @return \think\response\Jsonp
     */
    function do_alipay($code)
    {
        $payment = new \app\common\model\Trade();
        /** @var \app\common\model\Trade $payment_item */
        $payment_item = $payment->get(["code" => $code, "is_pay" => 0]);
        if (empty($payment_item)) {
            response_json(Code::FAIL);
        }
        $fee = $payment_item->value;
        $fee = abs($fee);


        #app 支付处理订单状态
        common_vendor('alipay_Aop.aop.AopClient');
        common_vendor('alipay_Aop.aop.request.AlipayTradeAppPayRequest');
        $aop = new \AopClient();
        $aop->appId = config('alipay_appid');
        $aop->rsaPrivateKey = config('alipay_rsa_private');
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = config("alipay_rsa_public");
        $body = "交易号{$code}付款";
        $subject = "交易付款";
        //异步通知地址  需http://格式的完整路径，不允许加?id=123这类自定义参数
        $notify_url = sprintf("%s/%s/code/%s",
            config('site_url'),
            "index/pay/alipay_notify_back",
            $code); //服务器异步通知页面路径
        $bizcontent = "{\"body\":\"" . $body . "\","
            . "\"subject\": \"" . $subject . "\","
            . "\"out_trade_no\": \"" . $code . "\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"" . $fee . "\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        $request = new \AlipayTradeAppPayRequest();
        $request->setNotifyUrl($notify_url);
        $request->setBizContent($bizcontent);
        $response = $aop->sdkExecute($request);
        response_json(Code::NONE, $response);
    }


    /**
     * 微信支付
     * 参数  code 交易码
     * @param $code
     * @return \think\response\Jsonp
     * @throws \WxPayException
     */
    public function do_weixin($code)
    {
        $payment = new \app\common\model\Trade();
        /** @var \app\common\model\Trade $payment_item */
        $payment_item = $payment->get(["code" => $code, "is_pay" => 0]);
        if (empty($payment_item)) {
            response_json(Code::FAIL);
        }
        $fee = $payment_item->value;
        define("WEIXIN_APPID", APP_WEIXIN_APPID);
        define("WEIXIN_APPSECRET", APP_WEIXIN_APPSECRET);
        define("WEIXIN_MCHID", APP_WEIXIN_MCHID);
        define("WEIXIN_KEY", APP_WEIXIN_KEY);
        common_vendor('AppWxpay.WxPayApi');
        $fee = $fee * 100;
        define("WX_NOTIFY_URL", sprintf("%s/%s/code/%s",
            config('site_url'),
            "member/pay/app_weixin__notifyurl",
            $code));
        $subject = "新桃源交易{$code}";
        $unifiedOrder = new \WxPayUnifiedOrder();
        $unifiedOrder->SetBody($subject);//商品或支付单简要描述
        $unifiedOrder->SetOut_trade_no($code);
        $unifiedOrder->SetTotal_fee($fee);
        $unifiedOrder->SetTrade_type("APP");
        $result = \WxPayApi::unifiedOrder($unifiedOrder);
        response_json(Code::NONE);
    }

    /**
     * 余额支付
     * 参数
     * code
     * password
     * @param int $code
     * @param int $password
     */
    function do_yue($code = 0, $password = 0)
    {
        $password = Crypt::pwd($password);
        /** @var \app\common\model\Users $user */
        $user = Session::get_local_user();
        if (empty($user)) {
            response_json(Code::NO_LOGIN);
        }
        $fund = $user->getUserFund();
        if ($fund->password === $password) {
            PaySuccess::setPaymentType(Trade::PAYMENT_YUE);
            $status = PaySuccess::do_();
            if ($status) {
                response_json(Code::NONE);
            } else {
                response_json(Code::FAIL);
            }
        }
        response_json(Code::YUE_PWD_ERROR);
    }
}